package com.luzh.myspring.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.luzh.myspring.beans.BeanException;
import com.luzh.myspring.beans.factory.ConfigurableListableBeanFactory;
import com.luzh.myspring.beans.factory.config.BeanDefinition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 可以注册bean的容器（注册bean定义，预实例化）
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {

    //存放bean定义的容器
    private final Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();


    /**
     * 预实例化
     * @throws BeanException
     */
    @Override
    public void preInstantiateSingletons() throws BeanException {
        beanDefinitionMap.keySet().forEach((name) -> {
            if (beanDefinitionMap.get(name).isSingleton()) getBean(name);
        });
    }

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        if(StrUtil.isEmpty(beanName))
            throw new BeanException("Bean name is empty");
        if(beanDefinition==null)
            throw new BeanException("Bean definition is null");
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws BeanException {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null)
            throw new BeanException("No bean named '" + beanName + "' is defined");
        return beanDefinition;
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }

    /**
     * 返回指定类型的所有单例
     * @param type
     * @param <T>
     * @return
     * @throws BeanException
     */
    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeanException {
        Map<String, T> result = new HashMap<>();
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            Class<?> beanClass = beanDefinition.getBeanClass();
            //判断beanClass表示的类型是否可以通过标识转换或通过扩展引用转换为此type对象表示的类型。
            if (type.isAssignableFrom(beanClass)) {
                result.put(beanName, (T) getBean(beanName));
            }
        });
        return result;
    }

    /**
     * 返回指定类型的单例对象
     * @param requiredType
     * @param <T>
     * @return
     * @throws BeanException
     */
    @Override
    public <T> T getBean(Class<T> requiredType) throws BeanException {
        List<String> beanNames = new ArrayList<>();
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            Class<?> beanClass = entry.getValue().getBeanClass();
            if (requiredType.isAssignableFrom(beanClass)) {
                beanNames.add(entry.getKey());
            }
        }
        if (1 == beanNames.size()) {
            return getBean(beanNames.get(0), requiredType);
        }
        throw new BeanException(requiredType + "expected single bean but found " + beanNames.size() + ": " + beanNames);
    }
}
